/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.boudreaulocke.model.persistence.jpa;

import javax.persistence.EntityManager;

import com.boudreaulocke.model.persistence.IPersonDao;
import com.boudreaulocke.model.persistence.PersistentPerson;
import com.locke.library.persistence.dao.jpa.AbstractJpaDao;
import com.locke.library.persistence.dao.jpa.JpaQuery;
import com.locke.library.persistence.dao.query.AbstractDaoQuery;
import com.locke.library.persistence.dao.query.Clause;
import com.locke.library.persistence.dao.query.clauses.Descending;
import com.locke.library.persistence.dao.query.clauses.Match;

/**
 * Hibernate DAO for PersistentPerson objects.
 * 
 * @author Jonathan
 */
public class JpaPersonDao extends
		AbstractJpaDao<PersistentPerson, Long> implements
		IPersonDao
{
	/**
	 * Construct.
	 */
	public JpaPersonDao(final EntityManager entityManager)
	{
		super(entityManager, PersistentPerson.class);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public <C extends Clause> AbstractDaoQuery<PersistentPerson, Long> query(
			C... clauses)
	{
		return new JpaQuery<PersistentPerson, Long>(this,
				clauses)
		{
			@Override
			protected void onMatch(Match<PersistentPerson> match)
			{
				// NOTE: We could make a smart reflection-based query-by-example
				// implementation if we wanted to (and then you wouldn't need
				// this anonymous subclass at all), but for now we'll just
				// support a couple of hardwired properties of PersistentPerson
				PersistentPerson person = match.getObject();
				addMatchConstraint("name", person.getName());
				addMatchConstraint("phoneNumber", person.getPhoneNumber());
			}

			@Override
			protected void onDescending(Descending descending)
			{
				final String field = descending.getField();
				if (field.equals("phoneNumber"))
				{
					append("order by target.phoneNumber.areaCode desc, target.phoneNumber.prefix desc, target.phoneNumber.suffix desc");
				}
				else
					super.onDescending(descending);
			}
		};
	}
}
